package com.sun.elasticjob.job;

import com.alibaba.fastjson2.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.sun.elasticjob.entity.File;
import com.sun.elasticjob.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 文件备份任务
 */
@Slf4j
@Component
public class FileBackupJob implements SimpleJob {

    @Autowired
    private FileService fileService;

    /**
     * 任务调度执行方法
     * @param shardingContext
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("============开始执行FileBackupJob任务============");
        // 作业分片
        int shardingItem = shardingContext.getShardingItem();

        // 分片参数
        String shardingParam = shardingContext.getShardingParameter();
        log.info("作业分片：{} 分片参数：{}", shardingItem, shardingParam);

        // 获取备份文件
        List<File> files = fetchBackupFiles(shardingParam);

        // 文件备份
        backupFiles(files);
    }

    private List<File> fetchBackupFiles(String type) {
        return fileService.fetchFile(type, 1);
    }

    private void backupFiles(List<File> files) {
        if(!files.isEmpty()) {
            log.info("需要备份的数据：{}", JSON.toJSONString(files));
            fileService.backupFiles(files);
            log.info("任务备份完成");
        } else {
            log.info("没有需要备份的数据");
        }
    }

}
